import axios from 'axios'

const API_BASE_URL = 'http://localhost:2025'

// 创建axios实例
const adminApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加管理员token
adminApi.interceptors.request.use(
  config => {
    const adminToken = localStorage.getItem('adminToken')
    if (adminToken) {
      config.headers.Authorization = `Bearer ${adminToken}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
adminApi.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response?.status === 401) {
      // 管理员token过期，跳转到管理员登录页
      localStorage.removeItem('adminToken')
      localStorage.removeItem('adminInfo')
      localStorage.removeItem('adminTokenExpiry')
      window.location.href = '/admin/login'
    }
    return Promise.reject(error)
  }
)

// ============================= 管理员认证 =============================

export const adminAuth = {
  // 管理员登录
  login: (credentials) => adminApi.post('/api/admin/login', credentials),
  
  // 获取管理员信息
  getProfile: () => adminApi.get('/api/admin/profile'),
}

// ============================= 用户管理 =============================

export const userManagement = {
  // 获取用户列表
  getUsers: (page = 0, size = 10) => adminApi.get(`/api/admin/users?page=${page}&size=${size}`),
  
  // 获取用户详情
  getUserDetails: (userId) => adminApi.get(`/api/admin/users/${userId}`),
  
  // 更新用户信息
  updateUser: (userData) => adminApi.put(`/api/admin/users/${userData.userId}`, userData),
  
  // 删除用户
  deleteUser: (userId) => adminApi.delete(`/api/admin/users/${userId}`),
  
  // 批量删除用户
  batchDeleteUsers: (userIds) => adminApi.post('/api/admin/users/batch-delete', { userIds }),
  
  // 批量更新用户状态
  batchUpdateStatus: (userIds, status) => adminApi.post('/api/admin/users/batch-status', { userIds, status }),
}

// ============================= 音乐管理 =============================

export const musicManagement = {
  // 获取音乐列表
  getMusic: (page = 0, size = 10) => adminApi.get(`/api/admin/music?page=${page}&size=${size}`),
  
  // 上传音乐
  uploadMusic: (musicData) => adminApi.post('/api/admin/music', musicData),
  
  // 更新音乐
  updateMusic: (musicId, musicData) => adminApi.put(`/api/admin/music/${musicId}`, musicData),
  
  // 删除音乐
  deleteMusic: (musicId) => adminApi.delete(`/api/admin/music/${musicId}`),
  
  // 批量删除音乐
  batchDeleteMusic: (musicIds) => adminApi.post('/api/admin/music/batch-delete', { musicIds }),
}

// ============================= 分类管理 =============================

export const categoryManagement = {
  // 获取分类列表（分页）
  getCategories: (params = {}) => {
    const { page = 0, size = 10, sortBy = 'sortOrder', status, keyword } = params
    let url = `/api/admin/categories?page=${page}&size=${size}&sortBy=${sortBy}`
    if (status !== undefined && status !== '') url += `&status=${status}`
    if (keyword) url += `&keyword=${encodeURIComponent(keyword)}`
    return adminApi.get(url)
  },
  
  // 获取所有分类（不分页）
  getAllCategories: () => adminApi.get('/api/admin/categories/all'),
  
  // 获取分类详情
  getCategoryDetails: (categoryId) => adminApi.get(`/api/admin/categories/${categoryId}`),
  
  // 创建分类
  createCategory: (categoryData) => adminApi.post('/api/admin/categories', categoryData),
  
  // 更新分类
  updateCategory: (categoryId, categoryData) => adminApi.put(`/api/admin/categories/${categoryId}`, categoryData),
  
  // 删除分类
  deleteCategory: (categoryId) => adminApi.delete(`/api/admin/categories/${categoryId}`),
  
  // 批量删除分类
  batchDeleteCategories: (categoryIds) => adminApi.post('/api/admin/categories/batch-delete', { categoryIds }),
  
  // 批量更新分类状态
  batchUpdateCategoryStatus: (categoryIds, status) => adminApi.post('/api/admin/categories/batch-status', { categoryIds, status }),
}

// ============================= 文件上传 =============================

export const fileUpload = {
  // 上传封面图片
  uploadCover: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return adminApi.post('/api/upload/cover', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 上传音乐文件
  uploadSong: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return adminApi.post('/api/upload/song', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 批量上传
  uploadBatch: (songFile, coverFile) => {
    const formData = new FormData()
    if (songFile) formData.append('songFile', songFile)
    if (coverFile) formData.append('coverFile', coverFile)
    return adminApi.post('/api/upload/batch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 获取文件信息
  getFileInfo: (type, filename) => adminApi.get(`/api/files/info/${type}/${filename}`),
  
  // 清理孤立文件
  cleanOrphanFiles: () => adminApi.post('/api/admin/clean-files'),
}

// ============================= 统计信息 =============================

export const statistics = {
  // 获取统计信息
  getStatistics: () => adminApi.get('/api/admin/statistics'),
  
  // 获取热门音乐
  getHotMusic: (limit = 5) => adminApi.get(`/api/admin/hot-music?limit=${limit}`),
}

// ============================= 简化的API接口 =============================

// 为了向后兼容和简化使用，提供直接的方法调用
export const adminApiMethods = {
  // 认证
  ...adminAuth,
  
  // 用户管理
  ...userManagement,
  
  // 音乐管理
  ...musicManagement,
  
  // 分类管理
  ...categoryManagement,
  
  // 文件上传
  ...fileUpload,
  
  // 统计信息
  ...statistics,
}

export default adminApiMethods 